package com.neo.tiny.business.iot.api;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.neo.tiny.business.iot.entity.BusinessIotDeviceDO;
import com.neo.tiny.business.iot.service.BusinessIotDeviceService;
import com.neo.tiny.business.iot.vo.IotDeviceInfoReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: IoT设备操作
 * @Author: yqz
 * @CreateDate: 2023/1/15 21:11
 */
@Slf4j
@Service("ioTDeviceApiImpl")
public class IotDeviceApiImpl implements IotDeviceApi {


    @Autowired
    private BusinessIotDeviceService deviceService;

    @Override
    public void addDevice(String deviceId) {
        List<BusinessIotDeviceDO> list = deviceService.list(new LambdaQueryWrapper<BusinessIotDeviceDO>()
                .eq(BusinessIotDeviceDO::getDeviceId, deviceId));
        if (list.size() > 0) {
            return;
        }
        BusinessIotDeviceDO device = new BusinessIotDeviceDO();

        device.setDeviceId(deviceId);
        device.setAccessDate(LocalDateTime.now());
        device.setAccessStatus(1);
        deviceService.save(device);
    }

    @Override
    public void updateDeviceInfo(IotDeviceInfoReq req) {
        if (StrUtil.isNotBlank(req.getDeviceId())) {
            deviceService.update(new LambdaUpdateWrapper<BusinessIotDeviceDO>()
                    .set(BusinessIotDeviceDO::getDeviceMac, req.getDeviceMac())
                    .set(BusinessIotDeviceDO::getDeviceIp, req.getDeviceIp())
                    .set(BusinessIotDeviceDO::getOnlineTime, LocalDateTime.now())
                    .eq(BusinessIotDeviceDO::getDeviceId, req.getDeviceId()));
        }
    }
}
